package com.autumn.platform.dao.schema.statement.original;

import org.apache.ibatis.builder.IncompleteElementException;
import org.apache.ibatis.builder.xml.XMLStatementBuilder;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.session.Configuration;

import com.autumn.platform.dao.component.impl.MybatisComponents;
import com.autumn.platform.dao.schema.parser.SchemaSqlMapperParserDelegate;
import com.autumn.platform.dao.schema.statement.StatementHandlerSupport;

public class CRUDStatementHandler extends StatementHandlerSupport {

    @Override
    public void handleStatementNode(Configuration configuration, SchemaSqlMapperParserDelegate delegate, XNode node) {
        String databaseId = configuration.getDatabaseId();
        if (databaseId != null) {
            buildStatementFromContext(configuration, delegate, node, databaseId);
        }
        buildStatementFromContext(configuration, delegate, node, null);
    }

    private void buildStatementFromContext(Configuration configuration, SchemaSqlMapperParserDelegate delegate, XNode node, String requiredDatabaseId) {
        XMLStatementBuilder statementParser = MybatisComponents.newXMLStatementBuilder(configuration, delegate.getBuilderAssistant(),
                node, requiredDatabaseId);
        try {
            statementParser.parseStatementNode();
        } catch (IncompleteElementException e) {
            configuration.addIncompleteStatement(statementParser);
        }
    }
}
